//
//  CarPriceCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/26/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class CarPriceCell: UITableViewCell {

    
    // MARK: - Outlets

    private lazy var separatorView = CellSeparator()
    
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 17, weight: .bold)
        lbl.textAlignment = .left
        lbl.sizeToFit()
        lbl.textColor = .black
        lbl.text = "Цена авто"
        lbl.numberOfLines = 0
        return lbl
    }()
    
    private lazy var hintLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = .systemFont(ofSize: 15)
        lbl.textColor = .black
        lbl.text = "Загружается..."
        lbl.numberOfLines = 0
        return lbl
    }()
    
    private lazy var valueLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = .systemFont(ofSize: 15)
        lbl.textColor = .black
        lbl.numberOfLines = 0
        return lbl
    }()
    
    private lazy var mainStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .equalSpacing
        stack.spacing = 12
        return stack
    }()
    
    
    // MARK: - Props
    
    private var stateNumber: String!
    private var carFullName:String!
    private var carPrice: Int?
    private var isLoaded = false
    
    // MARK: - Init
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension CarPriceCell {
    
    private func loadAveragePrice () {
        let request = URLRequest(url: Request(base: .garage).getUrl(path: "checkauto/average_price/\(stateNumber!)/"))
    
        self.isLoaded = true
        
        let dataTask = URLSession.shared.dataTask(with: request) { (data, _, _) in
            DispatchQueue.main.async {
                
                guard let jsonData = data else {
                    return self.handleError()
                }
                
                if let dic = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:Any] {
                    if let price = dic["average_price"] as? Int {
                        self.handleResponse(price: price)
                    } else {
                        self.handleError()
                    }
                } else {
                    self.handleError()
                }
            }
        }
        
        dataTask.resume()
    }
    
    private func handleError () {
        self.hintLbl.text = "Не удалось найти инфу"
    }
    
    private func handleResponse (price: Int) {
        let prefix = self.compare(price1: self.carPrice, price2: price) ? " " : " не "
        self.hintLbl.text = "Цена этого автомобиля" + prefix + "совпадает со средней ценой на похожие"
        mainStack.addArrangedSubview(valueLbl)
        self.valueLbl.attributedText = self.createPriceText(text: "Средняя цена на \(self.carFullName!) - ", price: "\(price) ₸")
    }
    
    private func createPriceText (text: String, price: String) -> NSMutableAttributedString {
        let normalAttrs = [NSAttributedString.Key.foregroundColor : UIColor.black]
        let priceAttrs = [NSAttributedString.Key.foregroundColor: UIColor.green]
        
        let normalText = NSMutableAttributedString(string: text, attributes: normalAttrs)
        let priceText = NSMutableAttributedString(string: price, attributes: priceAttrs)
        normalText.append(priceText)
        return normalText
    }
    
    private func compare (price1: Int?, price2: Int?) -> Bool {
        let firstNumber = price1 ?? 0 > price2 ?? 0 ? price1 : price2
        let secondNumber = firstNumber == price1 ? price2 : price1
        return Double(secondNumber!) * 1.2 >= Double(firstNumber ?? 0)
    }
}


extension CarPriceCell: ConfigurableCell {
    
    func configure(data object: MainViewModel.CarPriceItem?, index: Int) {
        if !isLoaded {
            if let data = object, data.carNumber != nil {
                self.stateNumber = data.carNumber?.fullNumber
                self.carFullName = data.fullCarName
                self.carPrice = data.carPrice
                self.loadAveragePrice()
            } else {
                self.hintLbl.text = "Не удалось найти инфу"
            }
        }
    }

    func returnData() -> MainViewModel.CarPriceItem? { return nil }
}



extension CarPriceCell {
    
    private func addViews () {
        contentView.addSubview(separatorView)
        contentView.addSubview(titleLbl)
        contentView.addSubview(mainStack)
        
        _ = mainStack.arrangedSubviews.map {
            mainStack.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        mainStack.addArrangedSubview(hintLbl)
        
        mainStack.snp.makeConstraints { (make) in
            make.top.equalTo(titleLbl.snp.bottom).offset(8)
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(separatorView.snp.top).offset(-22)
        }
        
        titleLbl.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalToSuperview().offset(22)
            make.height.equalTo(20)
        }
        
        separatorView.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
}


